package com.spzx.order.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spzx.domain.OrderInfo;
import com.spzx.domain.OrderItem;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 订单Service业务层处理
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    OrderLogMapper orderLogMapper;

    @Override
    public PageInfo<OrderInfo> selectUserOrderInfoList(Integer pageNum, Integer pageSize, Integer orderStatus) {

        PageHelper.startPage(pageNum, pageSize);
        // 默认已经登录用户ID
        Long userId=1L ;
        // 通过订单状态和用户id获取订单信息
        List<OrderInfo> orderInfos = orderInfoMapper.selectList(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderStatus, orderStatus).eq(OrderInfo::getUserId, userId));
        // 通过订单信息获取订单号
        List<Long> orderNos = orderInfos.stream().map(OrderInfo::getId).toList();
        // 通过订单号查询订单项信息，并封装到订单信息中
        orderNos.forEach(orderNo -> {
            List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderNo));
            orderInfos.stream().filter(orderInfo -> orderInfo.getId().equals(orderNo)).forEach(orderInfo -> orderInfo.setOrderItemList(orderItemList));
        });

        return new PageInfo<>(orderInfos);


    }

    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        // 通过订单号查询订单信息
        LambdaQueryWrapper<OrderInfo> orderInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderInfoLambdaQueryWrapper.eq(OrderInfo::getOrderNo, orderNo);
        OrderInfo orderInfo = orderInfoMapper.selectOne(orderInfoLambdaQueryWrapper);
        // 通过订单信息查询订单项信息
        if (orderInfo != null) {
            LambdaQueryWrapper<OrderItem> orderItemLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderItemLambdaQueryWrapper.eq(OrderItem::getOrderId, orderInfo.getId());
            List<OrderItem> orderItemList = orderItemMapper.selectList(orderItemLambdaQueryWrapper);
            orderInfo.setOrderItemList(orderItemList);
        }


        return orderInfo;
    }
}
